package com.tuozixuan.code.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.lang3.StringUtils;

import com.tuozixuan.code.model.DatasourceInfo;

public class JdbcContext {

	private String url;
	
	private String username;
	
	private String password;
	
	private String driverClassName;

	private Connection connection = null;
	
	public JdbcContext(String url, String username, String password) {
		this("com.mysql.cj.jdbc.Driver", url, username, password);
	}
	
	public JdbcContext(String driver, String url, String username, String password) {
		this.url = url;
		this.username = username;
		this.password = password;
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
	}
	
	public JdbcContext(DatasourceInfo datasourceInfo) {
		this.url = datasourceInfo.getUrl();
		this.username = datasourceInfo.getUsername();
		this.password = datasourceInfo.getPassword();
        try {
        	this.driverClassName = datasourceInfo.getDriverClassName();
        	if (StringUtils.isBlank(driverClassName)) {
        		driverClassName = "com.mysql.cj.jdbc.Driver";
        	}
        	
            Class.forName(driverClassName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
	}
	
    public Connection getConnection(){
    	try {
			connection = DriverManager.getConnection(url, username, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
        return connection;
    }
}
